package com.yc.jpyy.file.service.imp;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import Decoder.BASE64Decoder;

import com.yc.jpyy.base.config.Config;
import com.yc.jpyy.base.service.BaseService;
import com.yc.jpyy.file.dao.FileDao;
import com.yc.jpyy.file.service.FileService;
import com.yc.jpyy.utils.Tools;

@Service
public class FileServiceImpl extends BaseService implements FileService{
	
	@Autowired
	private FileDao fileDao;
	
	@SuppressWarnings("resource")
	@Override
	public Map<String, Object> uploadFile(Map<String, Object> paramsMap)
			throws Exception {
		Map<String,Object> resultMap = new HashMap<>();
		BASE64Decoder decoder = new BASE64Decoder();
		//Base64解码  
		byte[] buff = decoder.decodeBuffer(paramsMap.get("buff").toString());
		/*for(int i=0;i<buff.length;++i)  
        {  
            if(buff[i]<0)  
            {//调整异常数据  
            	buff[i]+=256;  
            }  
        }  */
		String extension = paramsMap.get("extension").toString();
		String fileType = paramsMap.get("filetype").toString();
		LocalDate now = LocalDate.now();
		String filePath = "/" + fileType + "/" + now.getYear() + "/" 
		                + now.getMonthValue() + "/" + UUID.randomUUID() + extension;
		File file = new File(Config.getFilePath() + filePath);  
		if (file.getParent() != null
				&& !new File(file.getParent()).exists()) {
			new File(file.getParent()).mkdirs();// （文件前面的路径不存在，则创建该路径）
		}
		if (!file.exists()) {
			file.createNewFile();// 如果不存在该文件，则创建
		}
        FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);  
            bos.write(buff);
            resultMap.put("returnCode", 1);
			resultMap.put("returnMsg", "上传成功");
			resultMap.put("ListData", filePath);
		} catch (FileNotFoundException e) {
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "上传出现异常");
		}catch (IOException e) {
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "上传出现异常");
		}
		return resultMap;
	}

	@SuppressWarnings("resource")
	@Override
	public Map<String, Object> uploadFiles(String fileInfo)
			throws Exception {
		Map<String,Object> resultMap = new HashMap<>();
		//Base64解码
		BASE64Decoder decoder = new BASE64Decoder();
		LocalDate now = LocalDate.now();
		String ListData = "";
		//JSON字符串转JSON对象
		JSONObject jsonObject = JSONObject.fromObject(fileInfo);
		//获取JSON对象中的JSON对象数组
		JSONArray jsonArray = jsonObject.getJSONArray("Info");
		int jsonArraySize = jsonArray.size();//获取数组长度
		for(int i = 0; i < jsonArraySize; i++ ){
			//JSON对象转JSON字符串
			String str = jsonArray.getJSONObject(i).toString();
			//JSON字符串转map
			Map<String,Object> paramsMaps = Tools.JsonToMap(str);
			byte[] buff = decoder.decodeBuffer(paramsMaps.get("buff").toString());
			String extension = paramsMaps.get("extension").toString();
			String fileType = paramsMaps.get("filetype").toString();
			String filePath = "/" + fileType + "/" + now.getYear() + "/" 
			                + now.getMonthValue() + "/" + UUID.randomUUID() + extension;
			File file = new File(Config.getFilePath() + filePath);  
			if (file.getParent() != null
					&& !new File(file.getParent()).exists()) {
				new File(file.getParent()).mkdirs();// （文件前面的路径不存在，则创建该路径）
			}
			if (!file.exists()) {
				file.createNewFile();// 如果不存在该文件，则创建
			}
	        FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(file);
	            BufferedOutputStream bos = new BufferedOutputStream(fos);  
	            bos.write(buff);
	            if(i == 0){
	            	ListData = filePath;
	            }else{
	            	ListData = ListData + "," + filePath;
	            }
			} catch (FileNotFoundException e) {
				resultMap.put("returnCode", 0);
				resultMap.put("returnMsg", "上传出现异常");
				return resultMap;
			}catch (IOException e) {
				resultMap.put("returnCode", 0);
				resultMap.put("returnMsg", "上传出现异常");
				return resultMap;
			}
		}
		resultMap.put("returnCode", 1);
		resultMap.put("returnMsg", "上传成功");
		resultMap.put("ListData", ListData);
		return resultMap;
	}
	
	@SuppressWarnings("resource")
	@Override
	public Map<String, Object> uploadFileByte(Map<String, Object> paramsMap)
			throws Exception {
		Map<String,Object> resultMap = new HashMap<>();
		byte[] buff = paramsMap.get("buff").toString().getBytes();
		String extension = paramsMap.get("extension").toString();
		String fileType = paramsMap.get("filetype").toString();
		LocalDate now = LocalDate.now();
		String filePath = "/" + fileType + "/" + now.getYear() + "/" 
		                + now.getMonthValue() + "/" + UUID.randomUUID() + extension;
		File file = new File(Config.getFilePath() + filePath);  
		if (file.getParent() != null
				&& !new File(file.getParent()).exists()) {
			new File(file.getParent()).mkdirs();// （文件前面的路径不存在，则创建该路径）
		}
		if (!file.exists()) {
			file.createNewFile();// 如果不存在该文件，则创建
		}
        FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);  
            bos.write(buff);
            resultMap.put("returnCode", 1);
			resultMap.put("returnMsg", "上传成功");
			resultMap.put("ListData", filePath);
		} catch (FileNotFoundException e) {
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "上传出现异常");
		}catch (IOException e) {
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "上传出现异常");
		}
		return resultMap;
	}
	
	
	
	
	@Override
	public Map<String, Object> addFile(Map<String, Object> paramsMap)
			throws Exception {
		Map<String,Object> resultMap = new HashMap<>();
		int k = fileDao.addFile(paramsMap);
		if(k <= 0){
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "新增失败");
		}else{
			resultMap.put("returnCode", 1);
			resultMap.put("returnMsg", "新增成功");
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> queryFileByName(Map<String, Object> paramsMap)
			throws Exception {
		Map<String,Object> resultMap = new HashMap<>();
		paramsMap.put("filenamelasts", paramsMap.get("filenamelasts").toString().split(","));
		List<Map<String,Object>> fileMap = fileDao.queryFileByName(paramsMap);
		if(fileMap != null && fileMap.size() > 0){
			resultMap.put("returnCode", 1);
			resultMap.put("returnMsg", "查询成功");
			resultMap.put("ListData", fileMap);
		}else{
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "查询失败");
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> deleteFile(Map<String, Object> paramsMap)
			throws Exception {
		Map<String,Object> resultMap = new HashMap<>();
		String[] filenamelasts = paramsMap.get("filenamelasts").toString().split(",");
		paramsMap.put("filenamelasts", filenamelasts);
		int k = fileDao.deleteFile(paramsMap);
		if(k <= 0){
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "删除失败");
		}else{
			for(int i = 0;i < filenamelasts.length;i ++){
				//删除本地图片
				File f = new File(Config.getFilePath()
						+ filenamelasts[i]);
				f.delete();
			}
			resultMap.put("returnCode", 1);
			resultMap.put("returnMsg", "删除成功");
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> updateAnnex(Map<String, Object> paramsMap)
			throws Exception {
		Map<String,Object> resultMap = new HashMap<>();
		int k = fileDao.updateAnnex(paramsMap);
		if(k <= 0){
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "修改失败");
		}else{
			resultMap.put("returnCode", 1);
			resultMap.put("returnMsg", "修改成功");
		}
		return resultMap;
	}

}
